<template>
     <div class="seach-suggestion">

        <!-- <van-cell title="搜" icon="search" ></van-cell>
        <van-cell title="索" icon="search" ></van-cell>
        <van-cell title="建" icon="search" ></van-cell>
        <van-cell title="议" icon="search" ></van-cell> -->
        <!-- <van-cell :title="text" icon="search"  v-for="(text,index) in suggestion" :key="index"></van-cell>
        <div v-html="htmlStr"></div> -->
        <van-cell v-for="(text,index) in suggestion" :key="index" @click="SuggestClick(text)">
            <template #title>
                <van-icon name="search"></van-icon>
                <div  v-html="Hightlight(text)" > </div>
            </template>
        </van-cell>
     </div>
</template>

<script>
import { ref, onMounted,watch, reactive, toRefs } from 'vue';
import { getSearchSuggestion } from '../../../api/search';
import { debounce } from "lodash";
 
function useHightlight(searchText)
{
    const  Hightlight=(text)=>{
        const hightStr=`<span style="color:red">${searchText}</span>`;
        const reg=new RegExp(searchText,"gi");
       //  console.log(text);
       return text.replace(reg,hightStr);

    }
    return {Hightlight}

}
function useSuggestClick()
{
    const sugClick=(text)=>{
        console.log("搜索建议点击",text);
    }
}
 

async function  loadSearchSuggestion(q,state) {

    try {
        const { data } = await getSearchSuggestion(q);
        console.log(data.data.suggestion);
        state.suggestion=data.data.suggestion;
    } catch (error) {
        console.error(error)
    } 
    return {}
    
 }
emit:['SuggestClick'];
export default {
//组件使用项目  
  props: { 
    searchText:{
         type:String  ,
         required:true
     }
 },
//使用组件 
 //components:{ArticleItem },
     setup(props,{emit}) {
        const state=reactive({
            suggestion:[],
            htmlStr:'hello <span style="color:red">world</span>'
        });

        const SuggestClick=function(sugtext)
        {
            emit('SuggestClick',sugtext);
        }
        
      
        watch(
            ()=>props.searchText,

         debounce( 
            function (newValue,oldValue) {
                console.log("setup watch newvalue",newValue);
                    loadSearchSuggestion(newValue,state);
                }
        ,500)
        
        
        
        
        ,{immediate:true})
          
     
        return {
          ...toRefs(state),
          ...useHightlight(props.searchText),
          ...useSuggestClick(),
          SuggestClick
        }
     },
 };
</script>
<style>
     .container {
     display: flex;
    }
</style>